package cmd

import (
	"ckeadm/cmd/runner"
	"ckeadm/constants"
	"fmt"
	"github.com/sirupsen/logrus"
	"github.com/urfave/cli"
)

func TransFormCommand() cli.Command {
	var transformFlags = []cli.Flag {
		runner.ConfigPathFlag,
		runner.LogLevelFlag,
	}

	return cli.Command {
		Name:   "transform",
		Usage:  "Bring the cluster Transform Configration",
		Action: runTransForm,
		Flags:  transformFlags,
	}
}

// runKubeletStart executes kubelet start logic.
func runTransForm(ctx *cli.Context) error {
	ckeComponents, ckeCluster, ckeNodes, err := runner.GetCRs(ctx.String("f"))
	if err != nil {
		return fmt.Errorf("failed to get components: %s", err.Error())
	}

	if ckeComponents == nil {
		config, err := runner.GetConfigFromFile(ctx.String("f"))
		if err != nil {
			return fmt.Errorf("error while get config from %s, err: %s", ctx.String("f"), err.Error())
		}
		logrus.SetLevel(logrus.Level(ctx.Int("v")))
		logrus.Debugf("configration get from %s, list here: \n%+v\n", ctx.String("f"), config)

		if err = WriteConfigFile(config, constants.AnsibleConfig, constants.AnsibleAllConfig); err != nil {
			return fmt.Errorf("error while write config: %s", err.Error())
		}
		logrus.Infof("installing configration create at: %s, %s\n", constants.AnsibleConfig, constants.AnsibleAllConfig)

		return nil
	}

	config, err := runner.GetConfigFromComponentFile(ckeComponents, ckeCluster, ckeNodes)
	if err != nil {
		return fmt.Errorf("error while get config from %s, err: %s", ctx.String("f"), err.Error())
	}
	logrus.SetLevel(logrus.Level(ctx.Int("v")))
	logrus.Debugf("configration get from %s, list here: \n%+v\n", ctx.String("f"), config)

	if err = WriteConfigFile(config, constants.AnsibleConfig, constants.AnsibleAllConfig); err != nil {
		return fmt.Errorf("error while write config: %s", err.Error())
	}
	logrus.Infof("installing configration create at: %s, %s\n", constants.AnsibleConfig, constants.AnsibleAllConfig)

	return nil
}
